package com.chinaunicom.order.domain.service;

import com.alibaba.fastjson.JSON;
import com.chinaunicom.common.constants.Constants;
import com.chinaunicom.common.constants.RocketDelayedLevel;
import com.chinaunicom.order.domain.gateway.IMarketingGateway;
import com.chinaunicom.order.domain.model.entity.*;
import com.chinaunicom.order.domain.model.valobj.OrderStatus;
import com.chinaunicom.order.domain.repository.IOrderRepository;
import com.chinaunicom.order.infrastructure.mq.DefaultProducer;
import com.chinaunicom.order.types.PayOrderTimeoutMessage;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author guomenghuai
 * @date 2024/1/15
 * @Description
 */
@Slf4j
@Service
public class OrderService extends AbstractOrderService {

    @Resource
    private IOrderRepository orderRepository;

    @Autowired
    private DefaultProducer defaultProducer;

    @Autowired
    private IMarketingGateway marketingGateway;

    @Override
    protected Integer doCalculateOrderAmount(ShopCartEntity shopCartEntity, List<ProductSkuEntity> productSkuList) {
        Map<String, ProductSkuEntity> productSkuMap = productSkuList.stream().collect(Collectors.toMap(ProductSkuEntity::getSkuCode, Function.identity()));

        List<OrderItemEntity> orderItemList = Lists.newArrayList();
        shopCartEntity.getOrderItemList().forEach(item -> {
            String skuCode = item.getSkuCode();

            ProductSkuEntity productSkuEntity = productSkuMap.get(skuCode);
            OrderItemEntity orderItemEntity = new OrderItemEntity();
            BeanUtils.copyProperties(item, orderItemEntity);
            item.setProductId(productSkuEntity.getProductId());
            item.setProductType(productSkuEntity.getProductType());
            item.setProductName(productSkuEntity.getProductName());
            item.setSalePrice(productSkuEntity.getCurrentPrice());
            item.setOriginalPrice(productSkuEntity.getOriginalPrice());

            orderItemEntity.setProductId(productSkuEntity.getProductId());
            orderItemEntity.setProductType(productSkuEntity.getProductType());
            orderItemEntity.setProductName(productSkuEntity.getProductName());
            orderItemEntity.setSalePrice(productSkuEntity.getCurrentPrice());
            orderItemEntity.setOriginalPrice(productSkuEntity.getOriginalPrice());
            orderItemList.add(orderItemEntity);
        });

        CalculateOrderEntity calculateOrderEntity = new CalculateOrderEntity();
        calculateOrderEntity.setUserId(shopCartEntity.getUserId());
        calculateOrderEntity.setSellerId(shopCartEntity.getSellerId());
        // TODO 优惠券信息
        //calculateOrderEntity.setCouponId(shopCartEntity.getCouponId());
        calculateOrderEntity.setOrderItemList(orderItemList);

        return marketingGateway.calculateOrderAmount(calculateOrderEntity);
    }

    @Override
    protected Long doSaveOrder(CreateOrderEntity createOrderEntity) {
        return orderRepository.saveOrder(createOrderEntity);
    }

    @Override
    protected PrePayOrderEntity doPrePayOrder(PrePayOrderRequestEntity prePayOrderEntity) {
        log.info("模拟预支付。。。");
        return null;
    }

    @Override
    protected void doSendPayOrderTimeoutDelayQueue(Long orderId, Long userId) {
        PayOrderTimeoutMessage message = new PayOrderTimeoutMessage();
        message.setOrderId(orderId);
        message.setUserId(userId);
        message.setOrderStatus(OrderStatus.CREATED.getCode());

        String msgJson = JSON.toJSONString(message);
        log.info("发送支付订单超时延迟消息：{}", msgJson);
        defaultProducer.sendMessage(Constants.RocketMqConstants.PAY_ORDER_TIMEOUT_DELAY_TOPIC, msgJson,
                RocketDelayedLevel.DELAYED_5m, "支付订单超时延迟消息", null, orderId.toString());
    }

    @Override
    public void payCallback(PayCallbackEntity payCallback) {
        log.info("模拟支付回调。。。");
    }
}
